<template>
  <div class="device-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">设备管理</h1>
      <p class="page-description">管理和监控您的设备状态</p>
    </div>

    <!-- 设备统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">🖥️</div>
          <div class="stat-content">
            <h3 class="stat-number">{{ deviceStats.total }}</h3>
            <p class="stat-label">总设备数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon online">🟢</div>
          <div class="stat-content">
            <h3 class="stat-number">{{ deviceStats.online }}</h3>
            <p class="stat-label">在线设备</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon offline">🔴</div>
          <div class="stat-content">
            <h3 class="stat-number">{{ deviceStats.offline }}</h3>
            <p class="stat-label">离线设备</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon warning">⚠️</div>
          <div class="stat-content">
            <h3 class="stat-number">{{ deviceStats.warning }}</h3>
            <p class="stat-label">异常设备</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 设备列表 -->
    <div class="device-list-section">
      <div class="section-header">
        <h2 class="section-title">设备列表</h2>
        <div class="section-actions">
          <el-button @click="fetchDeviceList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button type="primary" @click="addDevice">
            <el-icon><Plus /></el-icon>
            添加设备
          </el-button>
        </div>
      </div>

      <!-- 设备表格 -->
      <div class="device-table">
        <el-table :data="deviceList" style="width: 100%" stripe v-loading="loading">
          <el-table-column prop="name" label="设备名称" min-width="180">
            <template #default="scope">
              <div class="device-name">
                <span class="device-icon">{{ scope.row.icon }}</span>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="设备型号" min-width="120" class-name="hidden-sm" />
          <el-table-column prop="subject" label="监控对象" min-width="120" class-name="hidden-sm" />
          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              <el-tag 
                :type="getStatusType(scope.row.status)"
                size="small"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ip" label="IP地址" min-width="130" class-name="hidden-md" />
          <el-table-column prop="lastSeen" label="创建时间" min-width="150" class-name="hidden-lg" />
          <el-table-column prop="createBy" label="创建人" min-width="100" class-name="hidden-md" />
          <el-table-column prop="location" label="位置" min-width="120" class-name="hidden-lg" />
          <el-table-column label="操作" min-width="140" fixed="right">
            <template #default="scope">
              <el-button size="small" type="warning" @click="editDevice(scope.row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteDevice(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加设备对话框 -->
    <el-dialog
      v-model="addDeviceDialogVisible"
      title="添加设备"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="addDeviceFormRef"
        :model="addDeviceForm"
        :rules="addDeviceRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="addDeviceForm.deviceName"
            placeholder="请输入设备名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input
            v-model="addDeviceForm.deviceModel"
            placeholder="请输入设备型号"
            maxlength="50"
          />
        </el-form-item>
        
        <el-form-item label="监控对象" prop="subject">
          <el-input
            v-model="addDeviceForm.subject"
            placeholder="请输入监控对象"
            maxlength="100"
          />
        </el-form-item>
        
        <el-form-item label="设备API" prop="deviceApi">
          <el-input
            v-model="addDeviceForm.deviceApi"
            placeholder="请输入设备API地址，如：http://192.168.1.100:8080"
            maxlength="200"
          />
        </el-form-item>
        
        <el-form-item label="位置" prop="location">
          <el-input
            v-model="addDeviceForm.location"
            placeholder="请输入设备位置"
            maxlength="100"
          />
        </el-form-item>
        
        <el-form-item label="设备描述" prop="deviceDescription">
          <el-input
            v-model="addDeviceForm.deviceDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入设备描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addDeviceForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleAddDevice" :loading="addDeviceLoading">
            {{ addDeviceLoading ? '创建中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑设备对话框 -->
    <el-dialog
      v-model="editDeviceDialogVisible"
      title="编辑设备"
      width="600px"
      :before-close="handleCloseEditDialog"
    >
      <el-form
        ref="editDeviceFormRef"
        :model="editDeviceForm"
        :rules="editDeviceRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="editDeviceForm.deviceName"
            placeholder="请输入设备名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input
            v-model="editDeviceForm.deviceModel"
            placeholder="请输入设备型号"
            maxlength="50"
          />
        </el-form-item>
        
        <el-form-item label="监控对象" prop="subject">
          <el-input
            v-model="editDeviceForm.subject"
            placeholder="请输入监控对象"
            maxlength="100"
          />
        </el-form-item>
        
        <el-form-item label="设备API" prop="deviceApi">
          <el-input
            v-model="editDeviceForm.deviceApi"
            placeholder="请输入设备API地址，如：http://192.168.1.100:8080"
            maxlength="200"
          />
        </el-form-item>
        
        <el-form-item label="位置" prop="location">
          <el-input
            v-model="editDeviceForm.location"
            placeholder="请输入设备位置"
            maxlength="100"
          />
        </el-form-item>
        
        <el-form-item label="设备描述" prop="deviceDescription">
          <el-input
            v-model="editDeviceForm.deviceDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入设备描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="editDeviceForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button type="primary" @click="handleEditDevice" :loading="editDeviceLoading">
            {{ editDeviceLoading ? '更新中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import deviceAPI from '@/api/agriculture/xctl/device'

// 设备统计数据
const deviceStats = reactive({
  total: 0,
  online: 0,
  offline: 0,
  warning: 0
})

// 设备列表数据
const deviceList = ref([])
const loading = ref(false)

// 添加设备对话框相关
const addDeviceDialogVisible = ref(false)
const addDeviceLoading = ref(false)
const addDeviceFormRef = ref(null)

// 编辑设备对话框相关
const editDeviceDialogVisible = ref(false)
const editDeviceLoading = ref(false)
const editDeviceFormRef = ref(null)
const currentEditDevice = ref(null)

// 添加设备表单数据
const addDeviceForm = ref({
  deviceName: '',
  deviceModel: '',
  subject: '',
  deviceApi: '',
  location: '',
  deviceDescription: '',
  remark: ''
})

// 编辑设备表单数据
const editDeviceForm = ref({
  deviceName: '',
  deviceModel: '',
  subject: '',
  deviceApi: '',
  location: '',
  deviceDescription: '',
  remark: ''
})

// 添加设备表单验证规则
const addDeviceRules = {
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 100, message: '设备名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  deviceModel: [
    { required: true, message: '请输入设备型号', trigger: 'blur' },
    { min: 1, max: 50, message: '设备型号长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请输入监控对象', trigger: 'blur' },
    { min: 1, max: 100, message: '监控对象长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  deviceApi: [
    { required: true, message: '请输入设备API地址', trigger: 'blur' },
    { 
      pattern: /^https?:\/\/.+/, 
      message: '请输入有效的API地址，如：http://192.168.1.100:8080', 
      trigger: 'blur' 
    }
  ]
}

// 编辑设备表单验证规则（与添加设备相同）
const editDeviceRules = {
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 100, message: '设备名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  deviceModel: [
    { required: true, message: '请输入设备型号', trigger: 'blur' },
    { min: 1, max: 50, message: '设备型号长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请输入监控对象', trigger: 'blur' },
    { min: 1, max: 100, message: '监控对象长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  deviceApi: [
    { required: true, message: '请输入设备API地址', trigger: 'blur' },
    { 
      pattern: /^https?:\/\/.+/, 
      message: '请输入有效的API地址，如：http://192.168.1.100:8080', 
      trigger: 'blur' 
    }
  ]
}

// 获取设备列表
const fetchDeviceList = async () => {
  try {
    loading.value = true
    const response = await deviceAPI.getDeviceList()
    
    // 根据实际API响应结构处理数据
    if (response && response.rows) {
      // 转换API数据格式为组件需要的格式
      deviceList.value = response.rows.map(device => ({
        id: device.deviceId,
        name: device.deviceName,
        icon: getDeviceIcon(device.deviceModel),
        type: device.deviceModel,
        status: device.status === '0' ? 'online' : 'offline',
        ip: extractIpFromApi(device.deviceApi),
        lastSeen: device.updateTime || device.createTime,
        location: device.location,
        subject: device.subject,
        description: device.deviceDescription,
        remark: device.remark,
        createBy: device.createBy
      }))
      
      calculateStats()
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 根据设备型号获取图标
const getDeviceIcon = (deviceModel) => {
  if (deviceModel.includes('CAM')) return ''
  if (deviceModel.includes('SENSOR')) return ''
  if (deviceModel.includes('SERVER')) return ''
  return ''
}

// 从API地址中提取IP
const extractIpFromApi = (apiUrl) => {
  if (!apiUrl) return '-'
  
  const trimmedUrl = apiUrl.trim()
  
  // 如果直接是IP地址格式，直接返回
  const ipRegex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(:\d+)?$/
  const ipMatch = trimmedUrl.match(ipRegex)
  if (ipMatch) {
    return ipMatch[1] // 返回IP部分，不包括端口
  }
  
  // 尝试作为完整URL解析
  try {
    const url = new URL(trimmedUrl)
    return url.hostname
  } catch {
    // 如果不是完整URL，尝试提取IP地址模式
    const extractedIp = trimmedUrl.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/)
    if (extractedIp) {
      return extractedIp[1]
    }
    return trimmedUrl // 如果都无法解析，返回原始值
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    online: 'success',
    offline: 'danger',
    warning: 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    warning: '异常'
  }
  return statusMap[status] || '未知'
}

// 计算统计数据
const calculateStats = () => {
  deviceStats.total = deviceList.value.length
  deviceStats.online = deviceList.value.filter(device => device.status === 'online').length
  deviceStats.offline = deviceList.value.filter(device => device.status === 'offline').length
  deviceStats.warning = deviceList.value.filter(device => device.status === 'warning').length
}

// 添加设备
const addDevice = () => {
  addDeviceDialogVisible.value = true
}

// 处理添加设备
const handleAddDevice = async () => {
  if (!addDeviceFormRef.value) return
  
  try {
    // 表单验证
    await addDeviceFormRef.value.validate()
    
    addDeviceLoading.value = true
    
    // 调用API创建设备
    const deviceData = {
      deviceName: addDeviceForm.value.deviceName,
      deviceModel: addDeviceForm.value.deviceModel,
      subject: addDeviceForm.value.subject,
      deviceApi: addDeviceForm.value.deviceApi,
      location: addDeviceForm.value.location,
      deviceDescription: addDeviceForm.value.deviceDescription,
      remark: addDeviceForm.value.remark,
      status: '0' // 默认状态为在线
    }
    
    await deviceAPI.createDevice(deviceData)
    
    ElMessage.success('设备创建成功')
    
    // 关闭对话框并重置表单
    handleCloseDialog()
    
    // 重新获取设备列表
    fetchDeviceList()
    
  } catch (error) {
    console.error('创建设备失败:', error)
    if (error.message) {
      ElMessage.error('创建设备失败: ' + error.message)
    } else {
      ElMessage.error('创建设备失败，请稍后重试')
    }
  } finally {
    addDeviceLoading.value = false
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  addDeviceDialogVisible.value = false
  // 重置表单
  if (addDeviceFormRef.value) {
    addDeviceFormRef.value.resetFields()
  }
  // 清空表单数据
  addDeviceForm.value = {
    deviceName: '',
    deviceModel: '',
    subject: '',
    deviceApi: '',
    location: '',
    deviceDescription: '',
    remark: ''
  }
}



// 编辑设备
const editDevice = async (device) => {
  try {
    // 获取设备详细信息
    const response = await deviceAPI.getDeviceById(device.id)
    
    if (response && response.data) {
      const deviceData = response.data
      
      // 填充编辑表单
      editDeviceForm.value = {
        deviceName: deviceData.deviceName || '',
        deviceModel: deviceData.deviceModel || '',
        subject: deviceData.subject || '',
        deviceApi: deviceData.deviceApi || '',
        location: deviceData.location || '',
        deviceDescription: deviceData.deviceDescription || '',
        remark: deviceData.remark || ''
      }
      
      // 保存当前编辑的设备信息
      currentEditDevice.value = device
      
      // 打开编辑对话框
      editDeviceDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取设备详情失败:', error)
    ElMessage.error('获取设备详情失败')
  }
}

// 处理编辑设备
const handleEditDevice = async () => {
  if (!editDeviceFormRef.value || !currentEditDevice.value) return
  
  try {
    // 表单验证
    await editDeviceFormRef.value.validate()
    
    editDeviceLoading.value = true
    
    // 调用API更新设备
    const deviceData = {
      deviceName: editDeviceForm.value.deviceName,
      deviceModel: editDeviceForm.value.deviceModel,
      subject: editDeviceForm.value.subject,
      deviceApi: editDeviceForm.value.deviceApi,
      location: editDeviceForm.value.location,
      deviceDescription: editDeviceForm.value.deviceDescription,
      remark: editDeviceForm.value.remark
    }
    
    await deviceAPI.updateDevice(currentEditDevice.value.id, deviceData)
    
    ElMessage.success('设备更新成功')
    
    // 关闭对话框并重置表单
    handleCloseEditDialog()
    
    // 重新获取设备列表
    fetchDeviceList()
    
  } catch (error) {
    console.error('更新设备失败:', error)
    if (error.message) {
      ElMessage.error('更新设备失败: ' + error.message)
    } else {
      ElMessage.error('更新设备失败，请稍后重试')
    }
  } finally {
    editDeviceLoading.value = false
  }
}

// 关闭编辑对话框
const handleCloseEditDialog = () => {
  editDeviceDialogVisible.value = false
  // 重置表单
  if (editDeviceFormRef.value) {
    editDeviceFormRef.value.resetFields()
  }
  // 清空表单数据
  editDeviceForm.value = {
    deviceName: '',
    deviceModel: '',
    subject: '',
    deviceApi: '',
    location: '',
    deviceDescription: '',
    remark: ''
  }
  // 清空当前编辑设备
  currentEditDevice.value = null
}

// 删除设备
const deleteDevice = (device) => {
  ElMessageBox.confirm(
    `确定要删除设备 "${device.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deviceAPI.deleteDevice(device.id)
      ElMessage.success('删除成功')
      // 重新获取设备列表
      fetchDeviceList()
    } catch (error) {
      console.error('删除设备失败:', error)
      ElMessage.error('删除设备失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时初始化数据
onMounted(() => {
  fetchDeviceList()
})
</script>

<style scoped>
.device-management {
  padding: 24px;
  background: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .device-management {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px !important;
  }
  
  .page-description {
    font-size: 14px !important;
  }
  
  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start !important;
  }
  
  .section-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .device-table {
    padding: 16px;
    overflow-x: auto;
  }
}

@media (max-width: 480px) {
  .device-management {
    padding: 12px;
  }
  
  .stats-section {
    margin-bottom: 24px;
  }
  
  .stat-card {
    padding: 16px !important;
  }
  
  .section-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .section-actions .el-button {
    width: 100%;
  }
}

.page-header {
  margin-bottom: 32px;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.stats-section {
  margin-bottom: 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  background: #f0f0f0;
}

.stat-icon.online {
  background: #f0f9ff;
}

.stat-icon.offline {
  background: #fef2f2;
}

.stat-icon.warning {
  background: #fffbeb;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 4px 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.device-list-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.section-actions {
  display: flex;
  gap: 12px;
}

.device-table {
  padding: 24px;
}

.device-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.device-icon {
  font-size: 18px;
}

/* 表格列响应式隐藏 */
:deep(.el-table .hidden-sm) {
  display: none;
}

@media (min-width: 769px) {
  :deep(.el-table .hidden-sm) {
    display: table-cell;
  }
}

@media (max-width: 1024px) {
  :deep(.el-table .hidden-md) {
    display: none;
  }
}

@media (max-width: 1200px) {
  :deep(.el-table .hidden-lg) {
    display: none;
  }
}

/* 表格容器响应式 */
.device-table {
  overflow-x: auto;
}

@media (max-width: 768px) {
  .device-table :deep(.el-table) {
    min-width: 600px;
  }
  
  .device-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}

/* 添加设备对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 对话框响应式 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 2vh auto;
  }
  
  :deep(.el-form-item__label) {
    font-size: 14px;
  }
  
  :deep(.el-input__inner) {
    font-size: 14px;
  }
}
</style>